/**
 * 提货码兑换和展示 201827  mxm
 */
define(function(require,exports,module) {
    var myPub = require('./public');
    var scrollLoad = require('./scrollLoading');

    var oGoodCordTxt = $('.js_goodCordTxt');
    var oGiftMa_TipTxt = $('.js_giftMa_tipTxt');
    var oSubmitGiftMa = $('.js_submitGiftMa');

    var oClearBtn = $('.js_clearBtn');

    var offTap = true;                      // 阻止多次点击
    var moreTapOffTime = null;              // 多次点击定时器
    var bSubmitOff = false;                 // 校验按钮是否可点击
    var bPwdOff = false;                    // 校验按钮是否可点击
    var maxLength = 22;                     // 提货码输入框的最长内容
    var maxLengthPwd = 6;                   // 密码最长内容

    var errorTip = [
        '在使用提货码前，请先输入提货码编号验证',
        '提货码编号错误，请重新输入',
        '提货码密码不能为空，请输入',
        '提货码密码错误，请重新输入',
        // '通过验证，提货码已过期，请在失效码中查看',
        // '通过验证，提货码已完成提货，请在失效码中查看',
        // '该提货码已被其他用户绑定，请勿重复绑定',
        // '尊敬的用户您今日输入的错误提示已达上限，24小时后才能重新输入'
    ];
    var layerTip = ['在使用提货码之前需要绑定您的手机号', '恭喜您，验证通过!'];
    var layerStyle_black = 'background-color:rgba(0,0,0, 0.6); color:#FFFFFF; border:none; border-radius: 5px; min-width: 50%;';

    var oPwdBlock = $('.js_pwdBlock');            // 密码分格区域
    var oPwdBlockLi =  oPwdBlock.find('li');        // 密码分块
    var oPwdBlockInput = $('.js_pwdBlockInput');  // 输入密码区域

    // var goodsDateUrl = '/deliveryCode/getCodeListOfDiffStatus';
    var goodsDateUrl = '/m/o/deliveryCode/1.0/getCodeListOfDiffStatus';
    /*var oTelescopic = $('.js_telescopic');
    var oTelescopicHeight = oTelescopic.height();
    var oMoreBtnBox = $('.js_moreBtnBox');*/

    var lazLoading = new myPub.lazLoadingImg();


    // 密码区域点击获取焦点
    oPwdBlock.on('click', function () {
        oPwdBlockInput.focus();
    });
    /*alert(oTelescopicHeight);
    oPwdBlockInput.focus(function () {
        oTelescopic.css({'height':oTelescopicHeight})
    });
    oGoodCordTxt.focus(function () {
        /!*oTelescopic.css({'height':oTelescopicHeight});
        alert(oTelescopic.height())*!/
        oMoreBtnBox.hide();
    });
    oGoodCordTxt.blur(function () {
        /!*oTelescopic.css({'height':oTelescopicHeight});
        alert(oTelescopic.height())*!/
        oMoreBtnBox.show();
    });*/

    // 密码输入框显示点状态设置
    oPwdBlockInput.on('input propertychange', function () {
        oPwdBlockLi.text('');
        if(oPwdBlockInput.val().length == 0) return;
        for(var i=0; i<oPwdBlockInput.val().length; i++) {
            oPwdBlockLi.eq(i).text('•');
        }


        ValiNumLetter(oPwdBlockInput, function () {
            bPwdOff = false;
        }, function () {
            bPwdOff = true;
        });
    });


    // 表单验证
    oGoodCordTxt.on('input propertychange',function() {
       /* oTelescopic.css({'height':oTelescopicHeight});
        alert(oTelescopic.height()+'111111'+oTelescopicHeight);*/
        // 通过前端验证 修改提示和改变检测状态
        var _splitVal = $(this).val().replace(/\s/g,'').replace(/(\d{4})(?=\d)/g,"$1 ");

        $(this).val(_splitVal);

        ValiNumLetter(oGoodCordTxt, function () {
            bSubmitOff = false;
            oGiftMa_TipTxt.text(errorTip[1]);
        }, function () {
            bSubmitOff = true;
            oGiftMa_TipTxt.text(errorTip[0]);
        });

        // 满足指定数字个数开始验证
        if(oGoodCordTxt.val().length === maxLength) {
            bSubmitOff ? oSubmitGiftMa.addClass('active') : oSubmitGiftMa.removeClass('active');
        }
        else {
            oSubmitGiftMa.removeClass('active');
        }
    });

    // 提交按钮操作
    oSubmitGiftMa.hammer().on('tap', function () {
        // 变亮状态 还有active
        if($(this).hasClass('active')) {
            // 防止多次点击
            if(offTap) {
                oGoodCordTxt.blur();
                offTap = false;

                if (isBind == "notBind"){
                    // 绑定手机号操作方法
                    CheckBlindMobile();
                }

                // 检测密码方法
                CheckPwd();

            }
            clearTimeout(moreTapOffTime);
            moreTapOffTime = setTimeout(function () {
                offTap = true;
            }, 500);
        }
    });

    // 清空按钮操作
    oClearBtn.hammer().on('tap', function () {
        oGoodCordTxt.val('');
        oGiftMa_TipTxt.text(errorTip[0]);
        oSubmitGiftMa.removeClass('active');
    });




    // 绑定手机弹框
    function CheckBlindMobile () {
        myPub.askLayer(layerTip[0], function () {
            // 立即绑定
            myPub.LayerCloseAll();
            var backHref = "${base}/deliveryCode/codeCenter";
            window.location.href = "${base}/h/login/bindMobile?backHref=" + backHref;
        }, function () {
            // 取消
            myPub.LayerCloseAll();
        }, 'no', null, ['立即绑定','取消']);

    }

    // 检测密码输入 
    function CheckPwd () {
        var codeSign = oGoodCordTxt.val().replace(/\s|\xA0/g,'');
        var codeKey = oPwdBlockInput.val();
        // '/deliveryCode/drawDeliverCode'  原来的接口
        var getCodeUrl = '/m/o/deliveryCode/1.0/drawDeliverCode';
        if(bPwdOff === true && oPwdBlockInput.val().length === maxLengthPwd) {
            G_JSON_POST(getCodeUrl,{codeSign:codeSign,codeKey:codeKey},function(data){
                if (data.ret.code == "61000") {
                    myPub.TipLayer("验证成功",null,function () {
                        window.location.href = "/deliveryCode/codeCenter";
                    });
                } else {
                    myPub.TipLayer(data.ret.message,null,function () {});
                    oGoodCordTxt.blur();
                    // oGiftMa_TipTxt.text(data.message);
                }
            })
        }
        else {


            if(oPwdBlockInput.val().length == 0) {
                myPub.TipLayer_noShade(errorTip[2], layerStyle_black);
            }
            else{
                myPub.TipLayer_noShade(errorTip[3], layerStyle_black);
            }
            // 清空密码
            oPwdBlockInput.val('');
            oPwdBlockLi.text('');
        }

    }

    /* 数字字母验证 */
    function ValiNumLetter(obj,fn1,fn2) {
        var reg = new RegExp("^[0-9 ]*$");
        if(!reg.test(obj.val())){
            if(fn1) fn1();
        }
        else{if(fn2) fn2();}
    }



    var oErrPage = $('.js_errPageArea');        // 错误提醒页面
    var oLoadingNull = $('.js_loadingNull');    // 没有更多
    var oLoading = $('.js_loading');            // 加载中
    var oGoodsListBox = $('.js_goodsListBox');
    var oScrollBox = $('.js_scrollBox');


    module.exports = {
        init: function() {
            connectHtml.AjaxData();
            // 消息提醒
            // connectHtml.MessageTip();
            scrollLoad.oScrollLoading.ScrollPage(function () {
                if(connectHtml.page > connectHtml.pageSum) {
                    oLoading.hide();
                    oLoadingNull.show();
                    return
                }
                else {
                    connectHtml.AjaxData();
                }
            });
        }
    };



    var connectHtml = {
        limit: 4,                       // 每次加载多少数据
        begin: 0,                       // 起始页码
        end: 0,                         // 结束页码
        page: 1,                        // 当前页码
        pageSum: 3,                        // 总页码
        // 设置广告数据
        AjaxData: function (index, fn) {
            var _this = this;

            G_JSON_POST(goodsDateUrl,{
                limit:_this.limit,
                start:(_this.page - 1) * _this.limit,
                invalid:invalid
            },function (data) {

                if( data.ret.code == "0") {
                   var dataItem = data.data;
                    _this.pageSum = Math.ceil(dataItem.total/_this.limit);
                    var dataList = dataItem.rows;

                    // 对应数据为0 return
                    if(dataList.length == 0 && _this.page < 2) {
                        oLoading.hide();
                        oLoadingNull.show();
                        oGoodsListBox.hide();
                        oErrPage.show();
                        return
                    }

                   _this.GoodsLiBoxHtml(dataList);
                    if(fn)fn();
                }
                else {
                    oLoading.hide();
                    oLoadingNull.show();
                    oGoodsListBox.hide();
                    oErrPage.show();
                }
            }, function () {
                // start
            }, function () {
                // end
            });
        },

        // 正常的数据
        GoodsLiBoxHtml : function (data, fn) {
            var _this = this;
            var shtml = '';

            // giftMa_used 已使用；  giftMa_old 已过期

            _this.begin = _this.page * _this.limit;
            _this.page++;

            for(var i=0; i<data.length; i++) {
                var codeState = '';
                var codeStateClass = '';
                if (data[i].signStatus == 1 || data[i].signStatus == 5){
                    if (data[i].timeStatus == 1){
                        codeState = '<a href="javascript:void(0)" class="btnStyle" style="margin-top: 1.8rem;background: #D3D3D3;border-color: #D3D3D3;color: #FFFFFF;">还未开始</a>';
                    }else{
                        if(data[i].currentCount==0) {
                            codeState = '<a href="' + BASE_URL + '/shop/pay/deliveryCodeConfirm?deliveryCodeSign=' + data[i].codeSign + '" class="btnStyle btn_BorderRed" style="margin-top: 1.8rem;">立即使用</a>';
                        }
                    }
                }else if (data[i].signStatus == 2){
                    codeStateClass = 'giftMa_used';
                    codeState = '<div class="giftMa_state"></div>';
                }else{
                    codeStateClass = 'giftMa_old';
                    codeState = '<div class="giftMa_state"></div>';
                }
                var _liData = data[i].items;

                var nValidityTime = data[i].deliveryDates.length;
                var dates='';
                if( nValidityTime > 1 ){
                    dates += '<span class="shrinkArea"><i>'+_this.DateFormat(data[i].deliveryDates[0].beginDate) + '-' + _this.DateFormat(data[i].deliveryDates[0].endDate)+'<a class="shrink iconStyle js_shrink icon-chevron-up"></a></i></span>';
                    dates += '<span class="shrinkPlace js_shrinkPlace" style="display: none;">';
                    for(var j = 1; j < nValidityTime; j++){
                        dates += '<span>'+_this.DateFormat(data[i].deliveryDates[j].beginDate) + '-' + _this.DateFormat(data[i].deliveryDates[j].endDate)+'</span>';
                    }
                    dates +='</span>'
                }else{
                    dates += '<span class="box12">'+_this.DateFormat(data[i].deliveryDates[0].beginDate) + '-' + _this.DateFormat(data[i].deliveryDates[0].endDate)+'</span>';
                }
                var always = "有效期";
                if(data[i].always==1){
                    always = "永久有效";
                }

                dates = dates.substr(0,dates.length-5);
                shtml += '<div class="transactionSuc backWhite '+codeStateClass+'">';
                if(data[i].deliveryType==1){
                    shtml += '   <p class="transTip">总计可提货'+data[i].deliveryCount+'次，提货周期为'+data[i].deliveryPeriod+'天，已提货'+data[i].currentCount+'次</p >';
                }
                shtml +=
                    '   <div class="myOrderTranT backWhite giftMaList">'+
                    '	    <div class="orderProduction goods_showChangeBox">'+
                    '			<div class="goods_showChange">'+
                    '				<ul class="goodsList clearfix js_goodsList">' +
                    _this.GoodsLiHtml(_liData) +
                    '               </ul>'+
                    '           </div>' +
                    '        </div>' +
                    '       <div class="onOrderFoot">'+
                    '           <div class="seletPrice HBox BoxCenter">'+
                    '               <div class="Bflex1">'+
                    '                   <p class="selPriLeft">'+
                    '                       <span>提货码编号：</span>'+
                    '                       <span>'+data[i].codeSign+'</span>'+
                    '                   </p>'+
                    '                   <p class="selPriLeft HBox selPriValidity">'+
                    '                       <span class="validityTime">'+always+':</span>'+
                    '                       <span class="Bflex1 validityArea">'+ dates + '</span>'+
                    '                   </p>'+
                    '                   <p class="selPriLeft">'+
                    '                       <span>提货后卖家将在'+data[i].deliveryTime+'小时内发货</span>'+
                    '                   </p>'+
                    '               </div>'+
                    codeState+
                    '           </div>'+
                    '       </div>'+
                    '   </div>' +
                    '</div>'
            };

            oGoodsListBox.append(shtml);
            lazLoading.DestroyLazLoadingImg();
            lazLoading.AddLazLoadingImg(oScrollBox[0]);
            if(oGoodsListBox.height() < oScrollBox.height()) {
                if(_this.page > _this.pageSum) {
                    oLoading.hide();
                    oLoadingNull.show();
                    return
                }
                else {
                    connectHtml.AjaxData();
                }
            }
            if(fn)fn();

        },

        GoodsLiHtml: function (data) {
            var shtml = '';
            for (var i=0; i<data.length; i++) {
                shtml +=
                    '<li>'+
                    '    <a class="BoxSelf" href="javascript:void(0)">'+
                    '        <figure>'+
                    '            <img class="js_lazyImg fadeIn" data-echo="'+HTTP_IMAGE_URL+data[i].goodsImg+'" src="/static_v4/image/loadImg.jpg">'+
                    '        </figure>'+
                    '        <aside class="priceArea VBox Bflex1">'+
                    '            <div class="Bflex1 priceArea_name">'+
                    '                <h4>'+data[i].goodsName+'</h4>'+
                    '                <p class="smallFont_tip">'+
                    '                    <span>规格:</span>'+
                    '                    <span>'+data[i].productName+'</span>'+
                    '                </p>'+
                    '            </div>'+
                    '            <div class="priceArea_price HBox">'+
                    '                <p class="selProNum">'+
                    '                    <span>数量：</span>'+
                    '                    <span class="proNumber">'+data[i].num+'</span>'+
                    '                </p>'+
                    '            </div>'+
                    '        </aside>'+
                    '    </a>'+
                    '</li>'
            }

            return shtml;
        },

        DateFormat:function(data) {
            var _data = data.split(' ');
            var reg = new RegExp( '-' , "g" );
            var _dataover = _data[0].replace(reg, '.');

            return _dataover;
        },

        // 消息提醒
        MessageTip: function () {
            var sTitle = '温馨提示';
            var sCont = '阳澄湖大闸蟹礼券提货时间为本年度9月21日-12月31日；10月中旬至11月大闸蟹更为肥美饱满，建议您避开开湖高峰期在此阶段提货品尝；今年未提货礼券，明年开湖日后仍然有效可提。';
            myPub.TipBtnLayer(sCont, sTitle, '确定', function () {
                myPub.LayerCloseAll();
            }, function () {}, function () {
                $('.layermbox .layermchild').css({
                    'width': '50%'
                });
                $('.layermcont').css({
                    'text-align': 'left',
                    'text-indent': '2em'
                })
            })
        }

    }

    // 在有效期的右边添加收缩标签
    var otelescopic = $('.js_telescopic');
    var dbTapOff = true;                        // 防止多次点击
    otelescopic.hammer().off('tap');
    otelescopic.hammer().on('tap', function (e) {
        if(dbTapOff){
            var _target = e.gesture.target;
            var $target;
            var $shrinkArea;
            _target.nodeName.toLowerCase() == 'a'? $target = $(_target): $target = $(_target).parents('a');

            if($target.length > 0){
                if($target[0].className == 'shrink iconStyle js_shrink icon-chevron-down' || $target[0].className == 'shrink iconStyle js_shrink icon-chevron-up'){
                    $shrinkArea = $target.parents('p').find('.js_shrinkPlace');
                    if($target.hasClass('icon-chevron-down')){
                        $target.removeClass('icon-chevron-down');
                        $target.addClass('icon-chevron-up');
                        $shrinkArea.fadeOut(100);
                    }else if($target.hasClass('icon-chevron-up')){
                        $target.addClass('icon-chevron-down');
                        $target.removeClass('icon-chevron-up');
                        $shrinkArea.fadeIn(400);
                    }
                }
            }
        }
    });
});

